package com.example.demo.util;

import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Classname ReadBin
 * @Description TODO
 * @Date 2019/12/17 16:02
 * @Created by yby
 */
public class ReadBin {
    public static void main(String[] args) throws Exception {

        bytesToFile();
        //测试CRC
        byte[] byteCRC8 ={0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0x10,0x11};
        byte[] byteCRC = {CRCUtil.getCRC8_MAXIM(byteCRC8)};
        System.out.println(bytesToHexString(byteCRC));
        System.out.println(CRCUtil.getCRC16_XMODEM(byteCRC8));
        System.out.println(bytesToHexString(CRCUtil.getCRC16_XMODEM(byteCRC8)));
        //System.out.println("取出来16进制："+bytesToHexString(CRCUtil.getCrc16(byteCRC8)));
        //CRCUtil.getCrc16();
         File file1 =new File("D:\\新森\\升级\\SelfLotteryAppPro_V1.0.0_20191217.bin");
        System.out.println("file.length="+file1.length());
        //String[] str = file1.getName().split("_");
        //System.out.println(str[1].getBytes().length); //版本
        //System.out.println(str[1].getBytes()[0]);
        //System.out.println(str[1].getBytes()[1]);
        //System.out.println(str[2].replaceAll(".bin","").getBytes().length);
        FileInputStream fis = new FileInputStream(file1);
        byte[] bytes1=new byte[new Long(file1.length()).intValue()];
        fis.read(bytes1); //读入到byte1数组中
        //fis.read(bytes1,0,new Long(file1.length()).intValue());
        int from =0;
        int to =12;
        byte[] byteCRC88 ={0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0x10,0x11};
        if(byteCRC88.length < to){
            System.out.println("长度已超出");
        }
        byte[] bytes888 = Arrays.copyOfRange(byteCRC88, from, to);//读到另一个byte数组中。
        System.out.println(bytesToHexString(bytes888));
        //FileUtil.getFile(bytes,"D:\\新森\\升级\\new","SelfLotteryAppPro_V1.0.0_20191217_new.txt");
        //FileUtil.byteArrayToFile(bytes,"D:\\新森\\升级\\new\\SelfLotteryAppPro_V1.0.0_20191217_new1.txt");
        /*File file2 =new File("D:\\新森\\升级\\new\\SelfLotteryAppPro_V1.0.0_20191217_new1.txt");
        FileInputStream fis2 = new FileInputStream(file2);
        byte[] bytes2=new byte[new Long(file2.length()).intValue()];
        fis2.read(bytes2);*/
        //System.out.println("长度="+file2.length());
        //System.out.println("新bytes="+bytes.length);
        //System.out.println("新bytes1="+Arrays.toString(bytes));

        //System.out.println("取出来16进制："+bytesToHexString(bytes1));
       // System.out.println(bytes1.length);
        /*FileUtil.byteArrayToFile(bytes,"D:\\新森\\升级\\new\\SelfLotteryAppPro_V1.0.0_20191217.bin");
        File file3 =new File("D:\\新森\\升级\\new\\SelfLotteryAppPro_V1.0.0_20191217.bin");
        FileInputStream fis22 = new FileInputStream(file2);
        byte[] bytes22 = Arrays.copyOfRange(bytes1, 2, 4);//读到另一个byte数组中。*/
        //System.out.println(bytesToHexString(bytes22));


        /*bytes[9]=(byte)0xff; //或者给第10位添加ff
        bytes[9]=(byte)255;
        bytes[9]=(byte)0x00;//或者
        bytes[9]=0;*/



        //bytesToFile();
    }

    //生成新的文件
    public static void  bytesToFile(){
        String srcPath = "D:\\新森\\升级\\SelfLotteryAppPro_V1.0.3_20200109.bin";
        String destPath = "D:\\新森\\升级\\new\\SelfLotteryAppPro_V1.0.3_20200109.bin";
        //todo 读取文件
        File file =new File(srcPath);
        System.out.println("file.length111="+file.length());
        FileInputStream fis =null;
        try {
            fis = new FileInputStream(file);
            byte[] byteFile=new byte[new Long(file.length()).intValue()];
            fis.read(byteFile);
            //第一步先末端补齐FF
            int add = 4-byteFile.length%4;
            System.out.println("add="+add);
            byte[] byteEnd = new byte[byteFile.length+add];
            if(byteFile.length%4 == 0){
                byteEnd = byteFile;
            }else {
                byte[] byte4 = new byte[add];
                for (int i = 0; i < add; i++) {
                    //byte[i]=(byte)0xff;
                    byte4[i] = (byte) 0xff;
                }
                System.arraycopy(byteFile, 0, byteEnd, 0, byteFile.length);
                System.arraycopy(byte4, 0, byteEnd, byteFile.length, add);
            }
            //获取文件的版本号
            String version = file.getName().split("_")[1];
            String time = file.getName().split("_")[2].replaceAll(".bin","");
            int length = new Long(file.length()).intValue()+add; //针对补齐FF的数据进行校验
            //第二步：版本号处理
            byte[] byteVersion = new byte[12];
            System.arraycopy(version.getBytes(),0,byteVersion,0,version.length());
            //版本日期
            byte[] byteTime = new byte[12];
            System.arraycopy(time.getBytes(),0,byteTime,0,time.length());
            //原数组长度
            byte[] byteLength=new byte[4];
            //length = 256;
            byteLength[3]=(byte) ((length>>24)&0xff);
            byteLength[2]=(byte) ((length>>16)&0xff);
            byteLength[1]=(byte) ((length>>8)&0xff);
            byteLength[0]=(byte) (length&0xff);
            /*System.out.println("bytes[0]="+byteLength[0]);
            System.out.println("bytes[1]="+byteLength[1]);
            System.out.println("bytes[2]="+byteLength[2]);
            System.out.println("bytes[3]="+byteLength[3])*/;
            //CRC16校验  对前面28个字节进行校验
            byte[] byte28 = new byte[28];

            System.arraycopy(byteVersion,0,byte28,0,12);
            System.arraycopy(byteTime,0,byte28,12,12);
            System.arraycopy(byteLength,0,byte28,24,4);
            CRCUtil crcUtil =new CRCUtil();
            //对源程序进行校验 +补足0xff后
            byte [] byteCRC16 = CRCUtil.getCRC16_XMODEM(byteEnd);
            //预留33个 补00
            byte[] byte63 = new byte[63];
            System.arraycopy(byte28,0,byte63,0,28);
            System.arraycopy(byteCRC16,0,byte63,28,2);
            //CRC16交换位置
            byte63[28] = byteCRC16[1];
            byte63[29] = byteCRC16[0];
            //System.out.println(Arrays.toString(byte63));

            //CRC8校验
            byte[] byte64 = new byte[64];
            byte byteCRC8=CRCUtil.getCRC8_MAXIM(byte63);
            System.arraycopy(byte63,0,byte64,0,63);
            byte64[63] = byteCRC8;
            System.out.println("byteCRC8="+byteCRC8);
            //第二步：数组合并中
            byte[] bytes = new byte[length+64];
            System.arraycopy(byte64,0,bytes,0,64);
            System.arraycopy(byteEnd,0,bytes,64,length);
            System.out.println("length="+length);
            System.out.println(bytesToHexString(bytes));
            /*byte[] bytes4032 = new byte[4032];
            System.arraycopy(byteEnd,0,bytes4032,0,4032);
            byte [] byteCRC16_4032 = CRCUtil.getCRC16_XMODEM(byteEnd);
            System.out.println("byteCRC16_4032="+bytesToHexString(byteCRC16_4032));*/
            //第三步：最终数组 判断是否能被4整除
            //bytePre =new byte[11];
            //System.out.println(Arrays.toString(bytePre));
            /*int add = 4-bytePre.length%4;
            System.out.println("add="+add);
            byte[] bytes = new byte[bytePre.length+add];
            if(bytePre.length%4 == 0){
                bytes = bytePre;
            }else{
                byte [] byte4 =new byte[add];
                for (int i=0;i<add;i++){
                    //byte[i]=(byte)0xff;
                    byte4[i]=(byte)0xff;
                }
                System.arraycopy(bytePre,0,bytes,0,bytePre.length);
                System.arraycopy(byte4,0,bytes,bytePre.length,add);
            }*/
            FileUtil.byteArrayToFile(bytes,destPath);
            File file2 =new File(destPath);
            FileInputStream fis22 = new FileInputStream(file2);
            System.out.println("file2的长度="+file2.length());
            /*byte[] bytes222=new byte[new Long(file2.length()).intValue()];
            fis22.read(bytes222);*/ //读入到byte1数组中
            //System.out.println();
            //System.out.println("取出来16进制："+bytesToHexString(bytes222));
            //System.out.println(Arrays.toString(bytes));
            //System.out.println(bytes.length);
            //System.out.println(bytePre.length);
            //System.arraycopy(byteVersion,0,data3,0,12);
            //System.out.println(Arrays.toString(bytePre));
            //System.out.println("取出来16进制："+bytesToHexString(bytePre));
            //System.out.println("取出来16进制："+bytesToHexString(bytes));
            //System.arraycopy(data1,0,data3,0,data1.length);
            //System.arraycopy(data2,0,data3,data1.length,data2.length);

            //System.arraycopy(bytes,);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        } finally {
        }

    }


    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }
    public static int getValidLength(byte[] bytes){
        int i = 0;
        if (null == bytes || 0 == bytes.length)
            return i ;
        for (; i < bytes.length; i++) {
            if (bytes[i] == '\0')
                break;
        }
        return i + 1;
    }

    /**
     * 将byte数组转化为Object对象
     * @return
     */
    private static String toObject(byte[] bytes){

        String jsonString = "";
        jsonString = JSONObject.toJSONString(bytes);
        return jsonString;
    }

    /**
     * 16进制直接转换成为字符串(无需Unicode解码)
     *
     * @param hexStr
     * @return
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * 字符串转换成为16进制(无需Unicode编码)
     *
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            // sb.append(' ');
        }
        return sb.toString().trim();
    }


}
